package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntityAdvCost;
import com.loongtech.bi.entity.system.EntitySysProject;
import com.loongtech.bi.manager.system.AdvCostManager;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.manager.system.SysProjectManager;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * ClassName: AdvConfigAction
 *
 * @author liuchen
 *         description: 广告成本配置
 * @date 2016-11-14 下午5:04:18
 */
@RestController
@Scope("prototype")
@RequestMapping("/advcostconfig")
public class AdvCostConfigAction {
    @Resource
    private AdvCostManager managerBase;
    @Resource(name = "systemConfig")
    private SystemConfig systemConfig;
    @Resource
    private SysProjectManager sysProjectManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;

    /**
     * 查询
     */
    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(@RequestParam Integer curPage, @RequestParam Integer pageSize, EntityAdvCost entityConfig) {
        Page<List<EntityAdvCost>> list;
        try {
            list = managerBase.queryByCriteria(curPage, pageSize, entityConfig);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> add(EntityAdvCost entity) {
        if ("mid".equals(systemConfig.getServerType())) {
            if (entity.getGameId() == null) {
                return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
            }
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", entity.getGameId());
                params.put("id", entity.getId());
                params.put("ldate", entity.getLdate());
                params.put("platform", entity.getPlatform());
                params.put("agent", entity.getAgent());
                params.put("channelName", entity.getChannelName());
                params.put("cost", entity.getCost());
                params.put("rebate", entity.getRebate());
                params.put("discount", entity.getDiscount());
                params.put("roi", entity.getRoi());
                String url = project.getProjectUrl() + "/advcostconfig/add.do";
                System.out.println("广告cost请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    managerBase.persist(entity);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            List<EntityAdvCost> list = managerBase.findAll();
            ResultData<String> res = validate(entity, true, list);
            if (res != null) {
                return res;
            }
            try {
                managerBase.persist(entity);
                return ResultData.success();
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntityAdvCost entity) {
        if ("mid".equals(systemConfig.getServerType())) {
            if (entity.getGameId() == null) {
                return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
            }
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", entity.getGameId());
                params.put("id", entity.getId());
                params.put("ldate", entity.getLdate());
                params.put("platform", entity.getPlatform());
                params.put("agent", entity.getAgent());
                params.put("channelName", entity.getChannelName());
                params.put("cost", entity.getCost());
                params.put("rebate", entity.getRebate());
                params.put("discount", entity.getDiscount());
                params.put("roi", entity.getRoi());
                String url = project.getProjectUrl() + "/advcostconfig/modify.do";
                System.out.println("广告cost请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    managerBase.merge(entity);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            List<EntityAdvCost> list = managerBase.findAll();
            ResultData<String> res = validate(entity, false, list);
            if (res != null) {
                return res;
            }
            try {
                EntityAdvCost cur = managerBase.get(entity.getId());
                if (cur != null) {
                    managerBase.merge(entity);
                    return ResultData.success();
                } else {
                    return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(Integer id) {
        if ("mid".equals(systemConfig.getServerType())) {
            EntityAdvCost advEntity = managerBase.get(id);
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", advEntity.getGameId());
                params.put("id", advEntity.getId());
                String url = project.getProjectUrl() + "/advcostconfig/delete.do";
                System.out.println("广告cost请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    managerBase.removeById(id);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            try {
                EntityAdvCost cur = managerBase.get(id);
                if (cur != null) {
                    managerBase.removeById(id);
                    return ResultData.success();
                } else {
                    return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    public ResultData<String> upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file) throws IOException {
        System.out.println("upload file.......: ");
        if (file == null || file.getSize() <= 0 || file.getOriginalFilename() == null) {
            return new ResultData<>(RetCode.eEmptyUploadFile.getErrorcode(), RetCode.eEmptyUploadFile.getErrorMsg());
        }
        String fileName = file.getOriginalFilename();
        String id = UUID.randomUUID().toString();
        // 文件的相对路径
        String subPath = "AdvCostConfig_" + id + "_" + fileName;
        // 文件的绝对路径
        String filePath = systemConfig.getFileParentPath() + subPath;
        File tmpdir = new File(systemConfig.getFileParentPath());
        if (!tmpdir.exists()) {
            tmpdir.mkdir();
        }
        File newfile = new File(filePath);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newfile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultData<>(RetCode.eIOUploadFile.getErrorcode(), RetCode.eIOUploadFile.getErrorMsg());
        }
        return parseExcel(newfile);
    }

    public ResultData<String> parseExcel(File file) {
        try {
            List<EntityAdvCost> tmp = parseUploadedExcel(file);
            StringBuilder InsertSQLPre = new StringBuilder("insert into bi_advcost(id,ldate,platform,agent,channelName,cost,rebate,discount,roi) values ");
            if (tmp != null && tmp.size() > 0) {
                for (EntityAdvCost e : tmp) {
                    managerBase.persist(e);
                    InsertSQLPre.append("(").append(e.getId()).append(",'").append(e.getLdate()).append("','").append(e.getPlatform())
                            .append("','").append(e.getAgent()).append("','").append(e.getChannelName()).append("','").append(e.getCost()).append("','").append(e.getRebate()).append("','").append(e.getDiscount()).append("','").append(e.getRoi()).append("'),");
                }
                String isql = InsertSQLPre.substring(0, InsertSQLPre.length() - 1);
                syncInfoLogManager.add(tmp.get(0).getGameId().toString(), isql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(RetCode.eParseExcel.getErrorcode(), RetCode.eParseExcel.getErrorMsg());
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        return ResultData.success();
    }

    private List<EntityAdvCost> parseUploadedExcel(File file) throws Exception {
        List<EntityAdvCost> result = new ArrayList<>();
        InputStream input = new FileInputStream(file);
        Workbook wb = WorkbookFactory.create(input);
        Sheet tempSheet = wb.getSheetAt(0);
        if (tempSheet == null) {
            IOUtils.closeQuietly(input);
            System.out.println("Error---------------------------excel内容为空,数据错误！");
            throw new Exception("excel内容为空,数据错误！");
        }
        int rowNum = tempSheet.getLastRowNum();// 获得总行数
        for (int i = 0; i <= rowNum; i++) {
            Row row = tempSheet.getRow(i);
            if (row == null) {
                continue;
            }
            String gameId = ExcelUtils.getCellValue(row.getCell(0));
            String id = ExcelUtils.getCellValue(row.getCell(1));
            String ldate = ExcelUtils.getCellValue(row.getCell(2));
            String platform = ExcelUtils.getCellValue(row.getCell(3));
            String agent = ExcelUtils.getCellValue(row.getCell(4));
            String channelName = ExcelUtils.getCellValue(row.getCell(5));
            String cost = ExcelUtils.getCellValue(row.getCell(6));
            String rebate = ExcelUtils.getCellValue(row.getCell(7));
            String discount = ExcelUtils.getCellValue(row.getCell(8));
            String roi = ExcelUtils.getCellValue(row.getCell(9));

            if ("".equals(id) ||"".equals(gameId) || "".equals(ldate) || "".equals(cost) || "".equals(channelName) || "".equals(agent) || "".equals(platform) || "".equals(discount)
                    || "".equals(roi) || "".equals(rebate)) {
                continue;
            }

            EntityAdvCost e = new EntityAdvCost();
            e.setGameId(Integer.parseInt(gameId));
            e.setId(Integer.parseInt(id));
            e.setLdate(ldate);
            e.setPlatform(platform);
            e.setAgent(agent);
            e.setChannelName(channelName);
            e.setCost(cost);
            e.setRebate(rebate);
            e.setDiscount(discount);
            e.setRoi(roi);
            result.add(e);
        }
        IOUtils.closeQuietly(input);
        return result;
    }


    private ResultData<String> validate(EntityAdvCost ebp, boolean isAdd, List<EntityAdvCost> ebpList) {
        if (Utils.isEmptyStr(ebp.getLdate())) {
            return new ResultData<>(RetCode.eEmptyDate.getErrorcode(), RetCode.eEmptyDate.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getPlatform()) || "0".equals(ebp.getPlatform())) {
            return new ResultData<>(RetCode.eEmptyChanPlat.getErrorcode(), RetCode.eEmptyChanPlat.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getAgent())) {
            return new ResultData<>(RetCode.eEmptyAgent.getErrorcode(), RetCode.eEmptyAgent.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getChannelName())) {
            return new ResultData<>(RetCode.eEmptyChanName.getErrorcode(), RetCode.eEmptyChanName.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getCost())) {
            return new ResultData<>(RetCode.eEmptyCost.getErrorcode(), RetCode.eEmptyCost.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getRebate())) {
            return new ResultData<>(RetCode.eEmptyProfit.getErrorcode(), RetCode.eEmptyProfit.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getDiscount())) {
            return new ResultData<>(RetCode.eEmptyDisCountCost.getErrorcode(), RetCode.eEmptyDisCountCost.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getRoi())) {
            return new ResultData<>(RetCode.eEmptyProfitShare.getErrorcode(), RetCode.eEmptyProfitShare.getErrorMsg());
        }
        if (isAdd) {
            // 如果是添加，则ID不能重
            for (EntityAdvCost e : ebpList) {
                if (ebp.getId() == e.getId()) {
                    return new ResultData<>(RetCode.eIdExist.getErrorcode(), RetCode.eIdExist.getErrorMsg());
                }
            }
        }
        return null;
    }


//    public void updateDefault(EntityAdvDefaultConfig e) {
//        FacesContext context = FacesContext.getCurrentInstance();
//        if (validate(context, e)) {
//            managerDefaultBase.merge(e);
//            context.addMessage(null, new FacesMessage("修改成功！"));
//            initData();
//        }
//    }
//
//    private boolean validate(FacesContext context, EntityAdvDefaultConfig ebp) {
//
//        if (Utils.isEmptyStr(ebp.getIosRoi())) {
//            context.addMessage(null, new FacesMessage("IOS分成比例不能为空！"));
//            return false;
//        }
//        if (Utils.isEmptyStr(ebp.getAndroidRoi())) {
//            context.addMessage(null, new FacesMessage("安卓分成比例不能为空！"));
//            return false;
//        }
//        return true;
//    }

}
